<template>
  <TreeTableLayout>
    <template #tree>
      <Tree @query="doQuery" :gatewayType="-1"></Tree>
    </template>
    <template #table>
      <RightTableLayout :slotName="['search', 'operation', 'table']">
        <template #search>
          <Query :columns="columns" @query="doQuery"></Query>
        </template>
        <template #operation>
          <el-button type="primary" v-if="deviceFid" @click="add" v-show="enable">
            <el-icon>
              <DocumentAdd />
            </el-icon>
            {{ i18n.fy.新增电表电量 }}
          </el-button>
          <el-button type="primary" v-if="deviceFid" @click="exportData" style="float: right">
            <el-icon>
              <Position />
            </el-icon>
            {{ i18n.fy.export }}
          </el-button>
        </template>
        <template #table>
          <el-table :empty-text="i18n.fy.nodata" :data="data.tableData" border v-loading="data.loading"
            :element-loading-text="i18n.fy.loading">
            <el-table-column prop="index" :label="i18n.fy.序号" width="80" align="center">
              <template #default="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column prop="imei" :label="i18n.fy.电表电量编号" align="center" />
            <el-table-column prop="address" :label="i18n.fy.地址" width="280" align="center" />
            <el-table-column prop="yesterdayPowerConsumption" :label="i18n.fy.昨日功耗" width="280" align="center" />
            <el-table-column prop="totalPowerConsumption" :label="i18n.fy.总功耗" align="center" />
            <el-table-column prop="updatedAt" :label="i18n.fy.抄表时间" width="220">
              <template #default="scope">
                {{ scope.row.updatedAt.replaceAll("T", " ") }}
              </template>
            </el-table-column>
            <el-table-column :label="i18n.fy.operation" width="280" align="center">
              <template #default="scope">
                <el-button type="primary" size="small" :loading="gxloading" @click="upDate(scope.row)">
                  {{ i18n.fy.更新 }}
                </el-button>
                <el-button type="primary" size="small" @click="edit(scope.row)">
                  {{ i18n.fy.编辑 }}
                </el-button>
                <el-button type="primary" size="small" @click="gettails(scope.row)">
                  {{ i18n.fy.详情 }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-table :empty-text="i18n.fy.nodata" id="table-out" v-show="false" :data="data.tableData"
            v-loading="data.loading" :element-loading-text="i18n.fy.loading">
            <el-table-column prop="index" :label="i18n.fy.序号" width="80" align="center">
              <template #default="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column prop="imei" :label="i18n.language === 'zh-cn' ? '电表电量编号' : 'imei'" align="center" />
            <el-table-column prop="address" :label="i18n.language === 'zh-cn' ? '地址' : 'address'" width="280"
              align="center" />
            <el-table-column prop="yesterdayPowerConsumption"
              :label="i18n.language === 'zh-cn' ? '昨日功耗' : 'yesterdayPowerConsumption'" width="280" align="center" />
            <el-table-column prop="totalPowerConsumption"
              :label="i18n.language === 'zh-cn' ? '总功耗' : 'totalPowerConsumption'" align="center" />
            <el-table-column prop="updatedAt" :label="i18n.language === 'zh-cn' ? '抄表时间' : 'Meter reading time'"
              width="220">
              <template #default="scope">
                {{ scope.row.updatedAt.replaceAll("T", " ") }}
              </template>
            </el-table-column>
          </el-table>
        </template>
      </RightTableLayout>
    </template>
  </TreeTableLayout>
  <div id="saveOrUpdateDiv" style="display: none">
    <div style="padding: 20px">
      <div class="layui-form-item" style="width: 100%; float: none">
        <label class="layui-form-label" style="width: 116px; padding-right: 0">　当前电表电量：</label>
        <div class="layui-input-block" style="margin-left: 132px">
          <el-tag @close="closeTag(tag)" v-for="tag in oldtableData" :key="tag.imei" class="mx-1" closable> <img
              src="/src/assets/icon/db.png" style="width: 25px" /> {{ tag.imei }} </el-tag>
        </div>
      </div>
      <div class="layui-form-item" style="width: 100%; float: none">
        <label class="layui-form-label" style="width: 116px; padding-right: 0">新增新电表电量：</label>
        <div class="layui-input-block" style="margin-left: 132px">
          <el-select multiple filterable style="width: 95%" v-model="dataElectricMeters" class="m-2"
            :placeholder="i18n.language === 'zh-cn' ? '请选择电表电量' : 'Please select an electricity meter'"
            autocomplete="off">
            <el-option v-for="item in electricMetersList" :key="item.imei" :label="item.imei" :value="item.imei" />
          </el-select>
        </div>
      </div>
      <div class="layui-form-item submitBox">
        <div class="layui-input-block" style="margin-left: 0">
          <button type="button" @click="submit"
            class="layui-btn layui-btn-normal layui-btn-sm layui-icon layui-icon-release" lay-filter="doSubmit1">
            {{ i18n.fy.提交 }}
          </button>
          <button type="reset" @click="resetting"
            class="layui-btn layui-btn-warm layui-btn-sm layui-icon layui-icon-refresh">
            {{ i18n.fy.重置 }}
          </button>
        </div>
      </div>
    </div>
  </div>
  <div id="saveOrUpdateDiv2" style="display: none">
    <div style="padding: 20px">
      <div class="layui-form-item" style="width: 100%; float: none">
        <label class="layui-form-label">地址:</label>
        <div class="layui-input-block" style="margin-right: 41px">
          <el-input v-model="curRow.address" placeholder="请输入地址" />
        </div>
      </div>
      <div class="layui-form-item submitBox">
        <div class="layui-input-block" style="margin-left: 0">
          <button type="button" @click="submit2"
            class="layui-btn layui-btn-normal layui-btn-sm layui-icon layui-icon-release" lay-filter="doSubmit2">
            {{ i18n.fy.提交 }}
          </button>
          <button type="reset" @click="curRow.address = ''"
            class="layui-btn layui-btn-warm layui-btn-sm layui-icon layui-icon-refresh">
            {{ i18n.fy.重置 }}
          </button>
        </div>
      </div>
    </div>
  </div>
  <div id="saveOrUpdateDiv7" style="display: none">
    <div style="padding: 20px">
      <div class="layui-form-item" style="width: 100%; float: none">
        <div style="color: red; padding-left: 27px; padding-bottom: 11px">温馨提示：查询出来的数据可能与表格数据有差别</div>
        <label class="layui-form-label">选择年月:</label>
        <div class="layui-input-block" style="margin-right: 41px; display: flex">
          <el-date-picker v-model="months" type="month" placeholder="请选择年月" style="margin-right: 10px" />
          <el-button type="primary" @click="seach()">查询</el-button>
        </div>
      </div>
      <div class="layui-form-item" style="width: 100%; float: none; margin-bottom: 0" v-show="realAnnualRes[0]">
        <label class="layui-form-label" style="padding-top: 0px">合计:</label>
        <div class="layui-input-block" style="min-height: auto">
          <span v-if="realAnnualRes[0]" style="position: relative; top: 2px">{{ realAnnualRes[0].power.toFixed(2)
            }}</span>
          <el-button type="primary" size="small" v-if="deviceFid" @click="exportData2"
            style="float: right; margin-right: 40px; margin-top: -4px">
            <el-icon>
              <Position />
            </el-icon>导出</el-button>
        </div>
      </div>
      <div v-loading="realLoading">
        <div style="overflow: auto; height: 520px" v-if="realAnnualRes[0]">
          <table id="Mytable" border="1"
            style="margin-left: 20px; border-collapse: collapse; font-size: 14px; text-align: center; width: 96%">
            <tbody>
              <tr>
                <td style="margin-top: 10px; padding: 0 15px"><strong>日期</strong></td>
                <td style="padding: 5px 15px"><strong>电表电量</strong></td>
              </tr>
              <tr v-for="(item, i) in days">
                <td style="padding: 4px 15px">{{ i + 1 }}日</td>
                <td>{{ list[i + 1] == undefined ? "0" : list[i + 1] }}</td>
              </tr>
            </tbody>
          </table>
        </div>
        <div v-else class="noneData">
          {{ i18n.fy.nodata }}
        </div>
      </div>
      <div class="layui-form-item submitBox" style="width: 97%">
        <div class="layui-input-block" style="margin-left: 0">
          <button type="button" @click="close"
            class="layui-btn layui-btn-normal layui-btn-sm layui-icon layui-icon-release" lay-filter="doSubmit2">
            {{ i18n.language === "zh-cn" ? "关闭" : "submit" }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
defineOptions({ name: "ElectricityList" });
import TreeTableLayout from "@/views/workbench/components/TreeTableLayout.vue";
import RightTableLayout from "@/views/workbench/components/RightTableLayout.vue";
import Query from "@/components/query.vue";
import Tree from "@/components/tree.vue";

import { i18nStore } from "@/pinia/i18n";
const i18n = i18nStore();
const gxloading = ref(false);

import { upateSingleMeter } from "@/api/electricitymanageApi";
import FileSaver from "file-saver";
import * as XLSX from "xlsx";

import axios from "axios";
const {
  appContext: {
    config: { globalProperties },
  },
} = getCurrentInstance();
let $httpUrl = globalProperties.$httpUrl;
let columns = reactive({ imei: { label: "imei", queryValue: "" } });

let data = reactive({
  queryForm: {
    page: 1,
    limit: 100,
  },
  tableData: [],
  total: 0,
  dialog: false,
  form: {},
  rules: {
    name: [{ required: true, message: "请输入姓名", trigger: "change" }],
    role: [{ required: true, message: "请选择岗位", trigger: "change" }],
  },
});

const upDate = async (row) => {
  let params = { imei: row.imei };
  gxloading.value = true;
  const response = await upateSingleMeter(params);
  gxloading.value = false;
  if (response.code === 200) {
    if (response.data.Code === "0") {
      ElMessage.warning(`${response.data.Msg}`);
    } else {
      ElMessage.success(`${response.data.Msg}`);
    }
  } else {
    ElMessage.error(response.message);
  }
};

let mainIndex = "";
const add = () => {
  // 新增
  dataElectricMeters.value = [];
  getElectricMetersList();
  mainIndex = layer.open({
    type: 1,
    title: i18n.language === "zh-cn" ? "新增电表电量" : "addItem",
    content: $("#saveOrUpdateDiv"),
    area: ["800px", "600px"],
    offset: ["100px"],
    success: function (index) {
      //清空表单数据
      // $("#dataFrm")[0].reset();
      url = $httpUrl + "/role/insertRole";
    },
  });
};

const exportData = () => {
  var xlsxParam = { raw: true };
  var wb = XLSX.utils.table_to_book(document.querySelector("#table-out"), xlsxParam);
  var wbout = XLSX.write(wb, {
    bookType: "xlsx",
    bookSST: true,
    type: "array",
  });
  try {
    FileSaver.saveAs(new Blob([wbout], { type: "application/octet-stream" }), "电表电量信息.xlsx");
  } catch (e) {
    if (typeof console !== "undefined") console.log(e, wbout);
  }
  return wbout;
};
const exportData2 = () => {
  var xlsxParam = { raw: true };
  var wb = XLSX.utils.table_to_book(document.querySelector("#Mytable"), xlsxParam);
  var wbout = XLSX.write(wb, {
    bookType: "xlsx",
    bookSST: true,
    type: "array",
  });
  try {
    FileSaver.saveAs(new Blob([wbout], { type: "application/octet-stream" }), "电表电量详细信息.xlsx");
  } catch (e) {
    if (typeof console !== "undefined") console.log(e, wbout);
  }
  return wbout;
};

let mainIndex2 = "";
let curRow = ref("");
const edit = (item) => {
  // 编辑
  curRow.value = item;
  mainIndex2 = layer.open({
    type: 1,
    title: i18n.language === "zh-cn" ? "编辑" : "addItem",
    content: $("#saveOrUpdateDiv2"),
    area: ["800px", "500px"],
    offset: ["100px"],
    success: function (index) { },
  });
};

let months = ref();
let realLoading = ref(false);
let mainIndex3 = "";
const gettails = (item) => {
  curRow.value = item;
  realAnnualRes.value = [];
  mainIndex3 = layer.open({
    type: 1,
    title: i18n.language === "zh-cn" ? "详情" : "details",
    content: $("#saveOrUpdateDiv7"),
    area: ["800px", "800px"],
    offset: ["100px"],
    success: function (index) {
      var currentDate = new Date();
      currentDate.setDate(1);
      var firstDayOfMonth = currentDate.toISOString().slice(0, 10); // 输出格式为
      months.value = firstDayOfMonth + " 00:00:00";
      seach();
    },
  });
};
const submit2 = () => {
  let params2 = {
    deviceFid: deviceFid.value,
    electricMeter: curRow.value,
  };
  axios.put($httpUrl + "/access/updateElectricMeter", params2).then((res) => {
    layer.msg("保存成功");
    layer.close(mainIndex2);
  });
};
const onChanSize = (e) => {
  //修改分页数
  data.queryForm.page = 1;
  data.queryForm.limit = e;
  getList();
};
const onChanPage = (e) => {
  //修改分页
  data.queryForm.page = e;
  getList();
};

const del = (row) => {
  // 删除
  ElMessageBox.confirm("确认删除?", "提示").then(() => { });
};

let formRef = ref(null);
let oldtableData = ref([]);
const getList = (params) => {
  // 获取表格数据
  if (params == undefined) {
    return;
  }
  let imei = params.imei;
  data.loading = true;
  $axios
    .post("/access/getElectricMeters", {
      ...data.queryForm,
      ...params,
      deviceFid: deviceFid.value,
    })
    .then((res) => {
      data.loading = false;
      data.tableData = res.data.data;

      let arr = [];
      if (imei && data.tableData) {
        arr = data.tableData.filter((item) => {
          return item.imei.includes(imei);
        });
        data.tableData = arr;
      }
      oldtableData.value = JSON.parse(JSON.stringify(res.data.data));
    });
};
let deviceFid = ref();
const doQuery = (params) => {
  if (params.deviceFid) {
    deviceFid.value = params.deviceFid;
  }
  getList({ ...params, deviceFid: deviceFid.value });
};
const getWidth = () => {
  return window.innerWidth - 398 + "px";
};
const getHeight = () => {
  return window.innerHeight - 170 + "px";
};
const showType = (type) => {
  if (type == -1) return "系统";
  if (type == 0) return "云平台";
  if (type == 1) return "云产品";
  if (type == 2) return "云设备";
};
var tableIns;
var $ = "";
var layer = "";
var form = "";
var table = "";
var dtree = "";
var url = "";

var menuTree = "";

let imei = ref();
let oldElectricMetersList = [];
let electricMetersList = ref([]);
const getElectricMetersList = () => {
  $axios.post("/access/electricMeters", {}).then((res) => {
    electricMetersList.value = res.data.data;
    oldElectricMetersList = res.data.data;
  });
};
const resetting = () => {
  dataElectricMeters.value = [];
};
let dataElectricMeters = ref([]);
const submit = () => {
  let electricMeters = [];

  for (let j = 0; j < dataElectricMeters.value.length; j++) {
    let imei = dataElectricMeters.value[j];
    for (let i = 0; i < electricMetersList.value.length; i++) {
      if (electricMetersList.value[i].imei == imei) {
        electricMeters.push(electricMetersList.value[i]);
      }
    }
  }
  let params2 = {
    deviceFid: deviceFid.value,
    electricMeters: electricMeters,
  };
  for (let i = 0; i < oldtableData.value.length; i++) {
    params2.electricMeters.push(oldtableData.value[i]);
  }
  axios.put($httpUrl + "/access/electricMeters", params2).then((res) => {
    layer.msg("保存成功");
    layer.close(mainIndex);
    getList({});
  });
};
const closeTag = (tag) => {
  let imei = tag.imei;
  for (let i = oldtableData.value.length - 1; i >= 0; i--) {
    if (imei == oldtableData.value[i].imei) {
      electricMetersList.value.push(oldtableData.value[i]);
      oldtableData.value.splice(i, 1);
    }
  }
};
let enable = ref(false);
const getRole = (id) => {
  $axios
    .post(`/role/getRole`)
    .then((res) => {
      for (const i of res.data.data) {
        if (i.role_key === "Admin") {
          enable.value = true;
          break;
        }
      }
    })
    .catch((err) => { });
};

let realAnnualRes = ref([]);

const close = () => {
  layer.close(mainIndex3);
};
const showreaDate = (obj, i) => {
  if (obj == undefined) {
    return "";
  } else {
    var json = eval("(" + obj.day + ")");
    let n = json[i];

    if (n == undefined) {
      return (n = 0);
    } else {
      return json[i].toFixed(2);
    }
  }
};
let list = ref({});
const seach = () => {
  days.value = [];
  console.log(months.value);
  for (let i = 1; i <= getDays(new Date().getFullYear(), months.value.split("-")[1] - 1); i++) {
    days.value.push(i + i18n.fy.days);
  }
  if (months.value == "") {
    return false;
  }
  realLoading.value = true;
  console.log(months.value);
  let arr = months.value.split("-");
  let params = new FormData();
  params.append("year", arr[0]);
  params.append("mon", parseInt(arr[1]));
  params.append("name", curRow.value.imei);
  $.ajax({
    url: $httpUrl + "/operationDevice/getRealMeterReport",
    type: "POST",
    data: params,
    processData: false, // jQuery不要去处理发送的数据
    contentType: false, // jQuery不要去设置Content-Type请求头
    dataType: "json",
    success: function (res) {
      realAnnualRes.value = res.data;
      if (res.data.length > 0) {
        list.value = eval("(" + res.data[0].day + ")");
      }
      console.log(list.value);
      realLoading.value = false;
    },
  });
};
const getDays = (year, month) => {
  let days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  if (year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)) {
    days[1] = 29;
  }
  return days[month];
};
let days = ref([]);
let date = new Date();
let currtMonth = ref(new Date().getMonth() + 1);
onMounted(() => {
  const getMonth = date.getMonth() + 1;
  for (let i = 1; i <= getDays(new Date().getFullYear(), currtMonth.value - 1); i++) {
    days.value.push(i + i18n.fy.days);
  }
  getRole();
  getElectricMetersList();
  layui
    .extend({
      dtree: "/layui_ext/dist/dtree",
    })
    .use(["jquery", "layer", "form", "table", "dtree"], function () {
      $ = layui.jquery;
      layer = layui.layer;
      table = layui.table;
      dtree = layui.dtree;
    });
});
//打开分配菜单的弹出层
onBeforeMount(() => {
  getList({});
});
</script>

<style lang="scss" scoped>
.electricity-manage {
  display: flex;

  :deep(#saveOrUpdateDiv .el-input__wrapper) {
    background: none !important;
  }

  #Mytable td {
    padding: 4px 0 !important;
  }

  #saveOrUpdateDiv,
  #saveOrUpdateDiv2 {
    position: relative;
    height: 90%;
    overflow: hidden;
  }

  .submitBox {
    text-align: center;
    width: 100%;
    position: absolute;
    bottom: 0;
  }

  .noneData {
    text-align: center;
    padding-top: 97px;
  }

  .mx-1 {
    margin-right: 5px;
    margin-bottom: 10px;
    margin-top: 8px;
  }

  #Mytable tr:nth-child(2n) td {
    background: rgba(255, 255, 255, 0.1);
  }
}
</style>
